package tsli.acm.ctrl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import javazoom.upload.MultipartFormDataRequest;
import javazoom.upload.UploadBean;
import javazoom.upload.UploadException;
import javazoom.upload.UploadFile;
import tsli.acm.dao.SFCAgentStructureDAO;
import tsli.acm.database.Database;
import tsli.acm.model.SFCAgentStructure;
import tsli.acm.util.Excel;

/**
 * Servlet implementation class ACM2101Srvl
 */
public class ACM2101Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	private String successMessage = "";
	private String errorMessage = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ACM2101Srvl() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// get site_id

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");

		String vaProcessType = request.getParameter("process_type");
		int vnRow = 0;

		MultipartFormDataRequest voMultipartForm = null;
		UploadBean voUpload = new UploadBean();
		try {
			voMultipartForm = new MultipartFormDataRequest(request);

			voUpload.setFolderstore(request.getRealPath("/") + "assets/excel");
			voUpload.setWhitelist("*.jpg,*.png,*.gif,*.txt,*.xls,*.xlsx");
			voUpload.setOverwrite(true);
			voUpload.store(voMultipartForm, "files");

			Hashtable voFileHashtable = voMultipartForm.getFiles();
			UploadFile voFileUpload = (UploadFile) voFileHashtable.get("files");
			String nameFile = voFileUpload.getFileName();

			File voFile = new File(request.getRealPath("/") + "assets/excel/"
					+ nameFile);
			try {
				this.db = new Database();

				String filePath = request.getRealPath("/") + "assets/excel/"
						+ nameFile;

				Excel voExcel = new Excel();
				ArrayList<HashMap> voDataList = new ArrayList<HashMap>();

				if (voFile.getPath().indexOf("xlsx") != -1) {
					voDataList = voExcel.readXLSXFile(filePath);
				} else {
					voDataList = voExcel.readXLSFile(filePath);
				}
				vnRow = (voDataList.size()-1);
				for (int i = 1; i < voDataList.size(); i++) {
					addData(request, response, voDataList.get(i));
				}
			} catch (Exception edb) {
				PrintWriter voOut = response.getWriter();
				try {

				} finally {
					voOut.close();
				}
				edb.printStackTrace();
			} finally {
				db.close();
			}

		} catch (UploadException e) {
			e.printStackTrace();
		}
		
		PrintWriter out = response.getWriter();
		try {
			JSONObject voObject = new JSONObject();
			voObject.put("success", successMessage.trim()+" จำนวน "+vnRow+" แถว");
			voObject.put("error", errorMessage.trim());

			out.print(voObject.toJSONString());
		} finally {
			out.close();
		}
	}

	protected void addData(HttpServletRequest request,
			HttpServletResponse response, HashMap<Object, Object> map)
			throws ServletException, IOException {

		this.db = new Database();
		this.successMessage = "";
		this.errorMessage = "";
		boolean errorOccur = true;

		SFCAgentStructure voSFCAgentStructure = new SFCAgentStructure(
				map.get(0).toString().trim(), map.get(1).toString().trim()
				, map.get(2).toString().trim(),map.get(3).toString().trim()
				, map.get(4).toString().trim(), map.get(5).toString().trim(), map.get(6).toString().trim()
				, map.get(7).toString().trim(), map.get(8).toString().trim()
				, map.get(9).toString().trim(), map.get(10).toString().trim()
				, map.get(11).toString().trim(), map.get(12).toString().trim()
				, map.get(13).toString().trim(), map.get(14).toString().trim()
				, map.get(15).toString().trim(), map.get(16).toString().trim()
				, map.get(17).toString().trim(), map.get(18).toString().trim()
				, map.get(19).toString().trim(), map.get(20).toString().trim()
				, map.get(21).toString().trim(), map.get(22).toString().trim()
				, map.get(23).toString().trim(), map.get(24).toString().trim()
				, map.get(25).toString().trim(), map.get(26).toString().trim()
				, map.get(27).toString().trim(), (int)Double.parseDouble(map.get(28).toString().trim()));

		SFCAgentStructureDAO voSFCAgentStructureDAO = new SFCAgentStructureDAO(db);
		
		try {
			voSFCAgentStructureDAO.insertSFCAgentStructure(voSFCAgentStructure);
			db.commit();
			successMessage = "บันทึกข้อมูลเรียบร้อยแล้ว";
		} catch (Exception e) {
			// errorOccur = true สำหรับเงื่อนไขที่ set Account = "" เวลาผู้ใช้กด
			// save อีกรอบจะได้ไม่เข้าเงื่อนไขอัพเดท
			errorOccur = true;
			try {
				db.rollback();
				// SMErrorLogDAO.addLog(0, "CS21002", JDate.getDate(),
				// JDate.getTime(),vnUserId, "InsertCustomerSrvl",
				// e.getMessage(),vaUrlAddress, vaAgentBrowser);
				errorMessage = "เกิดข้อผิดพลาดในการเพิ่มข้อมูล กรุณาติดต่อผู้ดูแลระบบ";
			} catch (Exception ex) {
				errorMessage = "เกิดข้อผิดพลาด: " + ex.getMessage();
			}
		}

		
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
